using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using Microsoft.Practices.ServiceLocation;
using Castle.Core.Logging;

namespace Caramel.ServiceModel
{
	public class ServiceLocatorInstanceProvider : IInstanceProvider
	{
		public ServiceLocatorInstanceProvider(Type instanceType)
		{
			this.InstanceType = instanceType;
			this.Logger = NullLogger.Instance;
		}

		public Type InstanceType { get; private set; }

		public ILogger Logger { get; set; }

		#region IInstanceProvider Members

		public object GetInstance(InstanceContext instanceContext, Message message)
		{
			try
			{
				return ServiceLocator.Current.GetInstance(this.InstanceType);
			}
			catch (Exception e)
			{
				this.Logger.ErrorFormat(e, e.Message);

				throw e;
			}
		}

		public object GetInstance(InstanceContext instanceContext)
		{
			return this.GetInstance(instanceContext, null);
		}

		public void ReleaseInstance(InstanceContext instanceContext, object instance)
		{
		}

		#endregion
	}
}
